#include <iostream>
#include <sys/types.h>
#include <sys/socket.h>
#include <strings.h>
#include <cstring>
#include <netinet/in.h>
#include <arpa/inet.h>
#include "Log.hpp"

uint16_t defaultport = 8080;
std::string defaultip = "0.0.0.0";

Log lg;

enum{
    SOCKET_FAIL = 1,
    BIND_FAIL
};

class UdpServer
{
public:
    UdpServer(const std::string &ip = defaultip, const uint16_t &port = defaultport):sockfd_(0), ip_(ip), port_(port), isrunning_(false)
    {}
    void Init()
    {
        sockfd_ = socket(AF_INET, SOCK_DGRAM, 0);
        if(sockfd_ < 0)
        {
            lg(Fatal,"socket create fail, sockfd: %d", sockfd_);
            exit(SOCKET_FAIL);
        }
        lg(Info,"socket create success. sockfd: %d", sockfd_);

        struct sockaddr_in local;
        bzero(&local,sizeof(local));
        local.sin_family = AF_INET;
        local.sin_port = htons(port_);
        local.sin_addr.s_addr = inet_addr(ip_.c_str());
        
        if(bind(sockfd_, (struct sockaddr*)&local, sizeof(local)) < 0)
        {
            lg(Fatal,"bind fail, errno: %d, because %s", errno, strerror(errno));
            exit(BIND_FAIL);
        }
        lg(Info,"bind success, errno: %d, because %s", errno, strerror(errno));
    }

    void CheckUser(const struct sockaddr_in &client, const std::string &ip, const uint16_t &port)
    {
        
    }

    void Broadcast()
    {

    }

    void Run()
    {
        isrunning_ = true;
        char buffer[SIZE];
        while(isrunning_)
        {
            buffer[0] = 0;
            struct sockaddr_in client;
            socklen_t len = sizeof(client);
            ssize_t n = recvfrom(sockfd_, buffer, SIZE - 1, 0, (struct sockaddr*)&client, &len);
            if(n < 0)
            {
                lg(Fatal,"recive fail, errno: %d, because %s", errno, strerror(errno));
                continue;
            }

            uint16_t clientport = ntohs(client.sin_port);
            std::string clientip = inet_ntoa(client.sin_addr);
            CheckUser(client, clientip, clientport);

            std::string info = buffer;
            Broadcast();
            std::cout << buffer << std::endl;
        }
    }
    ~UdpServer()
    {
        if(sockfd_ > 0) close(sockfd_);
    }
private:
    int sockfd_;
    std::string ip_;
    uint16_t port_;
    bool isrunning_;
};